import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type { 
  IScheduleTemplate, 
  IScheduleTemplateCreateRequest, 
  IScheduleTemplateUpdateRequest,
  IScheduleTemplateQueryParams
} from '@/types/schedule/scheduleTemplate';
import type { 
  IScheduleInstance, 
  IScheduleInstanceCreateRequest, 
  IScheduleInstanceUpdateRequest,
  IScheduleInstanceQueryParams
} from '@/types/schedule/scheduleInstance';
import { 
  ScheduleTemplateStatusEnum, 
  ScheduleInstanceStatusEnum, 
  DayOfWeekEnum,
  ScheduleViewTypeEnum,
  ConflictTypeEnum
} from '@/types/schedule/enums';
import { scheduleService } from '@/services/schedule';
import type { IAsyncState, IFilterState } from '@/types/common/base';

/**
 * 冲突信息接口
 * @description 课程安排冲突的详细信息
 */
export interface IScheduleConflict {
  /** 冲突ID */
  id: string;
  /** 冲突类型 */
  type: ConflictTypeEnum;
  /** 冲突描述 */
  message: string;
  /** 冲突的课程模板或实例 */
  conflictingItems: Array<{
    id: string;
    type: 'template' | 'instance';
    name: string;
    time: string;
    date?: string;
  }>;
}

/**
 * 课表状态接口
 * @description 定义课表状态管理的完整接口
 */
export interface IScheduleState {
  // 数据状态 - 课程模板
  /** 课程安排模板列表 */
  templates: IScheduleTemplate[];
  /** 当前选中的模板 */
  selectedTemplate: IScheduleTemplate | null;
  /** 选中的模板ID列表（用于批量操作） */
  selectedTemplateIds: string[];
  
  // 数据状态 - 课程实例
  /** 课程实例列表 */
  instances: IScheduleInstance[];
  /** 当前选中的实例 */
  selectedInstance: IScheduleInstance | null;
  /** 选中的实例ID列表（用于批量操作） */
  selectedInstanceIds: string[];
  
  // 异步状态
  /** 模板异步操作状态 */
  templateAsync: IAsyncState;
  /** 实例异步操作状态 */
  instanceAsync: IAsyncState;
  
  // UI状态 - 视图控制
  /** 当前视图类型 */
  viewType: ScheduleViewTypeEnum;
  /** 当前选中的日期 */
  selectedDate: string;
  /** 当前选中的学生ID列表（用于混合视图） */
  selectedStudentIds: string[];
  /** 是否显示冲突检测 */
  showConflictDetection: boolean;
  
  // UI状态 - 表单和面板
  /** 是否显示模板表单 */
  showTemplateForm: boolean;
  /** 模板表单模式 */
  templateFormMode: 'create' | 'edit';
  /** 是否显示实例详情 */
  showInstanceDetail: boolean;
  /** 是否显示批量操作面板 */
  showBatchPanel: boolean;
  /** 是否显示冲突处理对话框 */
  showConflictDialog: boolean;
  
  // 筛选状态 - 模板
  /** 模板筛选条件 */
  templateFilters: IFilterState<{
    /** 学生ID筛选 */
    studentId?: string;
    /** 学生ID列表筛选 */
    studentIds?: string[];
    /** 课程ID筛选 */
    courseId?: string;
    /** 星期筛选 */
    dayOfWeek?: DayOfWeekEnum;
    /** 状态筛选 */
    status?: ScheduleTemplateStatusEnum;
    /** 是否有剩余次数 */
    hasRemainingCount?: boolean;
  }>;
  
  // 筛选状态 - 实例
  /** 实例筛选条件 */
  instanceFilters: IFilterState<{
    /** 学生ID筛选 */
    studentId?: string;
    /** 学生ID列表筛选 */
    studentIds?: string[];
    /** 课程ID筛选 */
    courseId?: string;
    /** 日期范围筛选 */
    dateFrom?: string;
    /** 日期范围筛选 */
    dateTo?: string;
    /** 状态筛选 */
    status?: ScheduleInstanceStatusEnum;
    /** 是否为补课 */
    isMakeup?: boolean;
  }>;
  
  // 冲突检测状态
  /** 检测到的冲突列表 */
  conflicts: IScheduleConflict[];
  /** 冲突检测异步状态 */
  conflictAsync: IAsyncState;
 
  // Actions - 模板数据操作
  /** 获取所有模板 */
  fetchTemplates: (queryParams?: IScheduleTemplateQueryParams) => Promise<void>;
  /** 添加模板 */
  addTemplate: (templateData: IScheduleTemplateCreateRequest) => Promise<void>;
  /** 更新模板 */
  updateTemplate: (id: string, templateData: Omit<IScheduleTemplateUpdateRequest, 'id'>) => Promise<void>;
  /** 删除模板 */
  deleteTemplate: (id: string) => Promise<void>;
  /** 生成课程实例 */
  generateInstances: (templateId: string) => Promise<void>;
  
  // Actions - 实例数据操作
  /** 获取所有实例 */
  fetchInstances: (queryParams?: IScheduleInstanceQueryParams) => Promise<void>;
  /** 根据日期获取实例 */
  fetchInstancesByDate: (date: string, studentIds?: string[]) => Promise<void>;
  /** 根据日期范围获取实例 */
  fetchInstancesByDateRange: (dateFrom: string, dateTo: string, studentIds?: string[]) => Promise<void>;
  /** 完成课程实例 */
  completeInstance: (id: string) => Promise<void>;
  /** 取消课程实例 */
  cancelInstance: (id: string, reason?: string) => Promise<void>;
  /** 添加补课实例 */
  addMakeupInstance: (templateId: string, date: string, startTime?: string, endTime?: string) => Promise<void>;
  
  // Actions - 冲突检测
  /** 检查模板冲突 */
  checkTemplateConflict: (templateData: IScheduleTemplateCreateRequest) => Promise<void>;
  /** 检查实例冲突 */
  checkInstanceConflict: (instanceData: IScheduleInstanceCreateRequest) => Promise<void>;
  /** 清除冲突信息 */
  clearConflicts: () => void;
  
  // Actions - 选择操作
  /** 选择模板 */
  selectTemplate: (template: IScheduleTemplate | null) => void;
  /** 切换模板选择状态 */
  toggleTemplateSelection: (templateId: string) => void;
  /** 选择所有模板 */
  selectAllTemplates: () => void;
  /** 清空模板选择 */
  clearTemplateSelection: () => void;
  /** 选择实例 */
  selectInstance: (instance: IScheduleInstance | null) => void;
  /** 切换实例选择状态 */
  toggleInstanceSelection: (instanceId: string) => void;
  /** 选择所有实例 */
  selectAllInstances: () => void;
  /** 清空实例选择 */
  clearInstanceSelection: () => void;
  
  // Actions - 视图控制
  /** 设置视图类型 */
  setViewType: (viewType: ScheduleViewTypeEnum) => void;
  /** 设置选中日期 */
  setSelectedDate: (date: string) => void;
  /** 设置选中学生ID列表 */
  setSelectedStudentIds: (studentIds: string[]) => void;
  /** 切换学生选择 */
  toggleStudentSelection: (studentId: string) => void;
  /** 设置冲突检测显示状态 */
  setShowConflictDetection: (show: boolean) => void;
  
  // Actions - UI操作
  /** 设置模板表单显示状态 */
  setShowTemplateForm: (show: boolean) => void;
  /** 设置模板表单模式 */
  setTemplateFormMode: (mode: 'create' | 'edit') => void;
  /** 设置实例详情显示状态 */
  setShowInstanceDetail: (show: boolean) => void;
  /** 设置批量操作面板显示状态 */
  setShowBatchPanel: (show: boolean) => void;
  /** 设置冲突对话框显示状态 */
  setShowConflictDialog: (show: boolean) => void;
  
  // Actions - 筛选操作
  /** 更新模板筛选条件 */
  updateTemplateFilters: (filters: Partial<IScheduleState['templateFilters']['filters']>) => void;
  /** 设置模板搜索关键词 */
  setTemplateSearchKeyword: (keyword: string) => void;
  /** 重置模板筛选条件 */
  resetTemplateFilters: () => void;
  /** 更新实例筛选条件 */
  updateInstanceFilters: (filters: Partial<IScheduleState['instanceFilters']['filters']>) => void;
  /** 设置实例搜索关键词 */
  setInstanceSearchKeyword: (keyword: string) => void;
  /** 重置实例筛选条件 */
  resetInstanceFilters: () => void;
  
  // Actions - 其他操作
  /** 重置状态 */
  reset: () => void;
  /** 刷新数据 */
  refresh: () => Promise<void>;
}

/**
 * 课表状态管理
 * @description 使用 Zustand 实现的课表状态管理
 */
export const useScheduleStore = create<IScheduleState>()(
  devtools(
    persist(
      immer((set, get) => ({
        // 初始状态
        templates: [],
        selectedTemplate: null,
        selectedTemplateIds: [],
        instances: [],
        selectedInstance: null,
        selectedInstanceIds: [],
        templateAsync: {
          loading: false,
          error: null,
          lastUpdated: null
        },
        instanceAsync: {
          loading: false,
          error: null,
          lastUpdated: null
        },
        viewType: ScheduleViewTypeEnum.WEEK,
        selectedDate: new Date().toISOString().split('T')[0],
        selectedStudentIds: [],
        showConflictDetection: false,
        showTemplateForm: false,
        templateFormMode: 'create',
        showInstanceDetail: false,
        showBatchPanel: false,
        showConflictDialog: false,
        templateFilters: {
          filters: {},
          searchKeyword: '',
          sortBy: 'startDate',
          sortOrder: 'asc'
        },
        instanceFilters: {
          filters: {},
          searchKeyword: '',
          sortBy: 'date',
          sortOrder: 'asc'
        },
        conflicts: [],
        conflictAsync: {
          loading: false,
          error: null,
          lastUpdated: null
        },

        // Actions 实现 - 模板数据操作
        fetchTemplates: async (queryParams?: IScheduleTemplateQueryParams) => {
          set((state) => {
            state.templateAsync.loading = true;
            state.templateAsync.error = null;
          });

          try {
            const result = await scheduleService.getAllTemplates(queryParams);
            if (result.success) {
              set((state) => {
                state.templates = result.data;
                state.templateAsync.loading = false;
                state.templateAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.templateAsync.loading = false;
                state.templateAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.templateAsync.loading = false;
              state.templateAsync.error = error instanceof Error ? error.message : '获取课程模板失败';
            });
          }
        },

        addTemplate: async (templateData: IScheduleTemplateCreateRequest) => {
          set((state) => {
            state.templateAsync.loading = true;
            state.templateAsync.error = null;
          });

          try {
            const result = await scheduleService.createTemplate(templateData);
            if (result.success) {
              set((state) => {
                state.templates.push(result.data);
                state.templateAsync.loading = false;
                state.showTemplateForm = false;
              });
            } else {
              set((state) => {
                state.templateAsync.loading = false;
                state.templateAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.templateAsync.loading = false;
              state.templateAsync.error = error instanceof Error ? error.message : '添加课程模板失败';
            });
            throw error;
          }
        },    
    updateTemplate: async (id: string, templateData: Omit<IScheduleTemplateUpdateRequest, 'id'>) => {
          set((state) => {
            state.templateAsync.loading = true;
            state.templateAsync.error = null;
          });

          try {
            const result = await scheduleService.updateTemplate(id, templateData);
            if (result.success) {
              set((state) => {
                const index = state.templates.findIndex(template => template.id === id);
                if (index !== -1) {
                  state.templates[index] = result.data;
                }
                if (state.selectedTemplate?.id === id) {
                  state.selectedTemplate = result.data;
                }
                state.templateAsync.loading = false;
                state.showTemplateForm = false;
              });
            } else {
              set((state) => {
                state.templateAsync.loading = false;
                state.templateAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.templateAsync.loading = false;
              state.templateAsync.error = error instanceof Error ? error.message : '更新课程模板失败';
            });
            throw error;
          }
        },

        deleteTemplate: async (id: string) => {
          try {
            const result = await scheduleService.deleteTemplate(id);
            if (result.success) {
              set((state) => {
                state.templates = state.templates.filter(template => template.id !== id);
                if (state.selectedTemplate?.id === id) {
                  state.selectedTemplate = null;
                }
                state.selectedTemplateIds = state.selectedTemplateIds.filter(selectedId => selectedId !== id);
              });
            } else {
              set((state) => {
                state.templateAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.templateAsync.error = error instanceof Error ? error.message : '删除课程模板失败';
            });
            throw error;
          }
        },

        generateInstances: async (templateId: string) => {
          set((state) => {
            state.instanceAsync.loading = true;
            state.instanceAsync.error = null;
          });

          try {
            const result = await scheduleService.generateInstances(templateId);
            if (result.success) {
              set((state) => {
                // 添加新生成的实例到列表中
                state.instances.push(...result.data);
                state.instanceAsync.loading = false;
              });
            } else {
              set((state) => {
                state.instanceAsync.loading = false;
                state.instanceAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.loading = false;
              state.instanceAsync.error = error instanceof Error ? error.message : '生成课程实例失败';
            });
          }
        },

        // Actions 实现 - 实例数据操作
        fetchInstances: async (queryParams?: IScheduleInstanceQueryParams) => {
          set((state) => {
            state.instanceAsync.loading = true;
            state.instanceAsync.error = null;
          });

          try {
            const result = await scheduleService.getAllInstances(queryParams);
            if (result.success) {
              set((state) => {
                state.instances = result.data;
                state.instanceAsync.loading = false;
                state.instanceAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.instanceAsync.loading = false;
                state.instanceAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.loading = false;
              state.instanceAsync.error = error instanceof Error ? error.message : '获取课程实例失败';
            });
          }
        },

        fetchInstancesByDate: async (date: string, studentIds?: string[]) => {
          set((state) => {
            state.instanceAsync.loading = true;
            state.instanceAsync.error = null;
          });

          try {
            const result = await scheduleService.getInstancesByDate(date, studentIds);
            if (result.success) {
              set((state) => {
                state.instances = result.data;
                state.instanceAsync.loading = false;
                state.instanceAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.instanceAsync.loading = false;
                state.instanceAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.loading = false;
              state.instanceAsync.error = error instanceof Error ? error.message : '获取日期课程实例失败';
            });
          }
        },

        fetchInstancesByDateRange: async (dateFrom: string, dateTo: string, studentIds?: string[]) => {
          set((state) => {
            state.instanceAsync.loading = true;
            state.instanceAsync.error = null;
          });

          try {
            const result = await scheduleService.getInstancesByDateRange(dateFrom, dateTo, studentIds);
            if (result.success) {
              set((state) => {
                state.instances = result.data;
                state.instanceAsync.loading = false;
                state.instanceAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.instanceAsync.loading = false;
                state.instanceAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.loading = false;
              state.instanceAsync.error = error instanceof Error ? error.message : '获取日期范围课程实例失败';
            });
          }
        },

        completeInstance: async (id: string) => {
          try {
            const result = await scheduleService.completeInstance(id);
            if (result.success) {
              set((state) => {
                const index = state.instances.findIndex(instance => instance.id === id);
                if (index !== -1) {
                  state.instances[index] = result.data;
                }
                if (state.selectedInstance?.id === id) {
                  state.selectedInstance = result.data;
                }
              });
            } else {
              set((state) => {
                state.instanceAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.error = error instanceof Error ? error.message : '完成课程实例失败';
            });
            throw error;
          }
        },

        cancelInstance: async (id: string, reason?: string) => {
          try {
            const result = await scheduleService.cancelInstance(id, reason);
            if (result.success) {
              set((state) => {
                const index = state.instances.findIndex(instance => instance.id === id);
                if (index !== -1) {
                  state.instances[index] = result.data;
                }
                if (state.selectedInstance?.id === id) {
                  state.selectedInstance = result.data;
                }
              });
            } else {
              set((state) => {
                state.instanceAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.error = error instanceof Error ? error.message : '取消课程实例失败';
            });
            throw error;
          }
        },

        addMakeupInstance: async (templateId: string, date: string, startTime?: string, endTime?: string) => {
          set((state) => {
            state.instanceAsync.loading = true;
            state.instanceAsync.error = null;
          });

          try {
            const result = await scheduleService.addMakeupInstance(templateId, date, startTime, endTime);
            if (result.success) {
              set((state) => {
                state.instances.push(result.data);
                state.instanceAsync.loading = false;
              });
            } else {
              set((state) => {
                state.instanceAsync.loading = false;
                state.instanceAsync.error = result.error;
              });
              throw new Error(result.error);
            }
          } catch (error) {
            set((state) => {
              state.instanceAsync.loading = false;
              state.instanceAsync.error = error instanceof Error ? error.message : '添加补课实例失败';
            });
            throw error;
          }
        },

        // Actions 实现 - 冲突检测
        checkTemplateConflict: async (templateData: IScheduleTemplateCreateRequest) => {
          set((state) => {
            state.conflictAsync.loading = true;
            state.conflictAsync.error = null;
          });

          try {
            const result = await scheduleService.checkTemplateConflict(templateData);
            if (result.success) {
              set((state) => {
                // Convert IConflictDetectionResult to IScheduleConflict[]
                state.conflicts = result.data.conflicts.map((conflict, index) => ({
                  id: `conflict_${index}_${Date.now()}`,
                  type: conflict.conflictType as any, // Convert to ConflictTypeEnum
                  message: conflict.description,
                  conflictingItems: [{
                    id: conflict.instanceId,
                    type: 'instance' as const,
                    name: conflict.courseName,
                    time: conflict.timeRange,
                    date: conflict.date
                  }]
                }));
                state.conflictAsync.loading = false;
                state.conflictAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.conflictAsync.loading = false;
                state.conflictAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.conflictAsync.loading = false;
              state.conflictAsync.error = error instanceof Error ? error.message : '检查模板冲突失败';
            });
          }
        },

        checkInstanceConflict: async (instanceData: IScheduleInstanceCreateRequest) => {
          set((state) => {
            state.conflictAsync.loading = true;
            state.conflictAsync.error = null;
          });

          try {
            const result = await scheduleService.checkInstanceConflict(instanceData);
            if (result.success) {
              set((state) => {
                // Convert IConflictDetectionResult to IScheduleConflict[]
                state.conflicts = result.data.conflicts.map((conflict, index) => ({
                  id: `conflict_${index}_${Date.now()}`,
                  type: conflict.conflictType as any, // Convert to ConflictTypeEnum
                  message: conflict.description,
                  conflictingItems: [{
                    id: conflict.instanceId,
                    type: 'instance' as const,
                    name: conflict.courseName,
                    time: conflict.timeRange,
                    date: conflict.date
                  }]
                }));
                state.conflictAsync.loading = false;
                state.conflictAsync.lastUpdated = Date.now();
              });
            } else {
              set((state) => {
                state.conflictAsync.loading = false;
                state.conflictAsync.error = result.error;
              });
            }
          } catch (error) {
            set((state) => {
              state.conflictAsync.loading = false;
              state.conflictAsync.error = error instanceof Error ? error.message : '检查实例冲突失败';
            });
          }
        },

        clearConflicts: () => {
          set((state) => {
            state.conflicts = [];
            state.conflictAsync.error = null;
          });
        },

        // Actions 实现 - 选择操作
        selectTemplate: (template: IScheduleTemplate | null) => {
          set((state) => {
            state.selectedTemplate = template;
          });
        },

        toggleTemplateSelection: (templateId: string) => {
          set((state) => {
            const index = state.selectedTemplateIds.indexOf(templateId);
            if (index > -1) {
              state.selectedTemplateIds.splice(index, 1);
            } else {
              state.selectedTemplateIds.push(templateId);
            }
          });
        },

        selectAllTemplates: () => {
          set((state) => {
            state.selectedTemplateIds = state.templates.map(template => template.id);
          });
        },

        clearTemplateSelection: () => {
          set((state) => {
            state.selectedTemplateIds = [];
          });
        },

        selectInstance: (instance: IScheduleInstance | null) => {
          set((state) => {
            state.selectedInstance = instance;
          });
        },

        toggleInstanceSelection: (instanceId: string) => {
          set((state) => {
            const index = state.selectedInstanceIds.indexOf(instanceId);
            if (index > -1) {
              state.selectedInstanceIds.splice(index, 1);
            } else {
              state.selectedInstanceIds.push(instanceId);
            }
          });
        },

        selectAllInstances: () => {
          set((state) => {
            state.selectedInstanceIds = state.instances.map(instance => instance.id);
          });
        },

        clearInstanceSelection: () => {
          set((state) => {
            state.selectedInstanceIds = [];
          });
        },

        // Actions 实现 - 视图控制
        setViewType: (viewType: ScheduleViewTypeEnum) => {
          set((state) => {
            state.viewType = viewType;
          });
        },

        setSelectedDate: (date: string) => {
          set((state) => {
            state.selectedDate = date;
          });
        },

        setSelectedStudentIds: (studentIds: string[]) => {
          set((state) => {
            state.selectedStudentIds = studentIds;
          });
        },

        toggleStudentSelection: (studentId: string) => {
          set((state) => {
            const index = state.selectedStudentIds.indexOf(studentId);
            if (index > -1) {
              state.selectedStudentIds.splice(index, 1);
            } else {
              state.selectedStudentIds.push(studentId);
            }
          });
        },

        setShowConflictDetection: (show: boolean) => {
          set((state) => {
            state.showConflictDetection = show;
          });
        },

        // Actions 实现 - UI操作
        setShowTemplateForm: (show: boolean) => {
          set((state) => {
            state.showTemplateForm = show;
            if (!show) {
              state.selectedTemplate = null;
            }
          });
        },

        setTemplateFormMode: (mode: 'create' | 'edit') => {
          set((state) => {
            state.templateFormMode = mode;
          });
        },

        setShowInstanceDetail: (show: boolean) => {
          set((state) => {
            state.showInstanceDetail = show;
            if (!show) {
              state.selectedInstance = null;
            }
          });
        },

        setShowBatchPanel: (show: boolean) => {
          set((state) => {
            state.showBatchPanel = show;
          });
        },

        setShowConflictDialog: (show: boolean) => {
          set((state) => {
            state.showConflictDialog = show;
          });
        },

        // Actions 实现 - 筛选操作
        updateTemplateFilters: (filters: Partial<IScheduleState['templateFilters']['filters']>) => {
          set((state) => {
            state.templateFilters.filters = { ...state.templateFilters.filters, ...filters };
          });
        },

        setTemplateSearchKeyword: (keyword: string) => {
          set((state) => {
            state.templateFilters.searchKeyword = keyword;
          });
        },

        resetTemplateFilters: () => {
          set((state) => {
            state.templateFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'startDate',
              sortOrder: 'asc'
            };
          });
        },

        updateInstanceFilters: (filters: Partial<IScheduleState['instanceFilters']['filters']>) => {
          set((state) => {
            state.instanceFilters.filters = { ...state.instanceFilters.filters, ...filters };
          });
        },

        setInstanceSearchKeyword: (keyword: string) => {
          set((state) => {
            state.instanceFilters.searchKeyword = keyword;
          });
        },

        resetInstanceFilters: () => {
          set((state) => {
            state.instanceFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'date',
              sortOrder: 'asc'
            };
          });
        },

        // Actions 实现 - 其他操作
        reset: () => {
          set((state) => {
            state.templates = [];
            state.selectedTemplate = null;
            state.selectedTemplateIds = [];
            state.instances = [];
            state.selectedInstance = null;
            state.selectedInstanceIds = [];
            state.templateAsync = {
              loading: false,
              error: null,
              lastUpdated: null
            };
            state.instanceAsync = {
              loading: false,
              error: null,
              lastUpdated: null
            };
            state.viewType = ScheduleViewTypeEnum.WEEK;
            state.selectedDate = new Date().toISOString().split('T')[0];
            state.selectedStudentIds = [];
            state.showConflictDetection = false;
            state.showTemplateForm = false;
            state.templateFormMode = 'create';
            state.showInstanceDetail = false;
            state.showBatchPanel = false;
            state.showConflictDialog = false;
            state.templateFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'startDate',
              sortOrder: 'asc'
            };
            state.instanceFilters = {
              filters: {},
              searchKeyword: '',
              sortBy: 'date',
              sortOrder: 'asc'
            };
            state.conflicts = [];
            state.conflictAsync = {
              loading: false,
              error: null,
              lastUpdated: null
            };
          });
        },

        refresh: async () => {
          const { fetchTemplates, fetchInstances } = get();
          await Promise.all([
            fetchTemplates(),
            fetchInstances()
          ]);
        }
      })),
      {
        name: 'schedule-store',
        partialize: (state) => ({
          templates: state.templates,
          instances: state.instances,
          viewType: state.viewType,
          selectedDate: state.selectedDate,
          selectedStudentIds: state.selectedStudentIds,
          templateFilters: state.templateFilters,
          instanceFilters: state.instanceFilters
        })
      }
    ),
    {
      name: 'schedule-store'
    }
  )
);